package com.spancer.contentcenter.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.spancer.contentcenter.domain.dto.user.UserDTO;
import com.spancer.contentcenter.feignclient.TestBaiduFeignClient;
import com.spancer.contentcenter.feignclient.TestUserCenterFeignClient;
import com.spancer.contentcenter.service.SpTestService;
import com.spancer.contentcenter.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * author by: mars
 * Date: 2020/8/11 8:30
 * Description:
 */
@RestController
@RequestMapping("/test")
@RefreshScope
public class TestController {

    @Autowired
    private DiscoveryClient discoveryClient;
    @Autowired
    private TestUserCenterFeignClient testUserCenterFeignClient;
    @Autowired
    private TestBaiduFeignClient testBaiduFeignClient;

    // nacos配置
    //@Value("${my.config}")
    //private String myConfig;

    //@GetMapping("/test-myconfig")
    //public String testMyConfig(){
    //    return this.myConfig;
    //}


    /**
     *
     * @Author mars
     * @Description 测试：服务发现，证明内容中心总能找到用户中心
     * DiscoveryClient  是springCloud提供的，不管是用Eureka/Console/Nacos都可用
     */
    @GetMapping("/test1")
    public List<ServiceInstance> setDiscoveryClient(){
        // 查询指定服务所有实例的信息
        return discoveryClient.getInstances("user-center");
    }

    /**
     *
     * @Author mars
     * @Description 测试：注册了哪些微服务
     */
    @GetMapping("/test2")
    public List<String> getService(){
        return discoveryClient.getServices();
    }

    @GetMapping("/test3")
    public UserDTO queryUser(UserDTO userDTO){
        return testUserCenterFeignClient.query(userDTO);
    }

    @GetMapping("/baidu")
    public String baidu(){
        return testBaiduFeignClient.index();
    }


    @Autowired
    private TestService testService;

    @GetMapping("/test-a")
    public String testA(){
        testService.common();
        return "test-A";
    }

    @GetMapping("/test-b")
    public String testB(){
        testService.common();
        return "test-B";
    }

    @GetMapping("/test-hot")
    @SentinelResource("hot")
    public String testHot(@RequestParam(required = false) String a,@RequestParam(required = false) String b){
        return a+ "  " + b;
    }

    // 代码配置流控规则
    @GetMapping("/test-add-flow-rule")
    public String testFlowRule(){
        return "success";
    }
    private void initFlowQpsRule() {
        List<FlowRule> rules = new ArrayList<>();
        // 可以设置资源名称
        FlowRule rule = new FlowRule("/shares/1");
        // set limit qps to 20
        rule.setCount(20);
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        rule.setLimitApp("default");
        rules.add(rule);
        FlowRuleManager.loadRules(rules);
    }

    // sentinel api
    @GetMapping("/test-sentinel-api")
    public String testSentinelApi(String a){
        return "success";
    }

    @Autowired
    private SpTestService spTestService;

    @GetMapping("/sp-test")
    public String spTest(){
        return spTestService.test();
    }

    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        UserDTO dto = new UserDTO();
        dto.setId(1);
        dto.setWxNickname("zhangsan");
        System.out.println(Optional.ofNullable(dto).map(UserDTO::getWxId).orElse("no wxId"));

        //Class clazz = dto.getClass();
        //Field field = clazz.getDeclaredField("id");
        //field.setAccessible(true);
        //System.out.println(ReflectionUtils.getField(field,dto));

        //List<String> list = Arrays.asList("1","2","3");
        //list.stream().peek(x-> System.out.println(x)).collect(Collectors.toList());

    }

    @GetMapping("/producerTest")
    public String producerTest(){
        testService.producerSendMsg();
        return "success";
    }

    @Autowired
    private RestTemplate restTemplate;


    // resttemplate-exchange() 实现token拦截
    @GetMapping("/rest/tokenRelay/{userId}")
    public ResponseEntity<UserDTO> tokenRelay(@PathVariable(value = "userId") String userId,HttpServletRequest request){
        // 获取token
        String token = request.getHeader("X-Token");
        // 设置token
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("X-Token",token);
        // 调用exchange()
        return this.restTemplate.exchange(
                "http://user-center/users/{userId}", // 远程服务
                HttpMethod.GET, // 连接请求方式
                new HttpEntity<>(httpHeaders),
                UserDTO.class, //返回值类型
                userId  // 入参
        );
    }
}

